package com.echo.code.thread.future.impl;

import com.echo.code.thread.future.Future;

/**
 * SimpleFuture Created by baiyap on 2018/9/24.
 */
public class SimpleFuture<T> implements Future<T> {

  private final Boolean lock = Boolean.FALSE;
  private T result;
  private boolean isDone = Boolean.FALSE;

  @Override
  public T get() throws InterruptedException {
    synchronized (lock) {
      // suspend
      while (isDone == lock.booleanValue()) {
        lock.wait();
      }
      return result;
    }
  }

  public void finish(T result) {
    synchronized (lock) {
      // balking
      if (isDone) {
        return;
      }
      this.result = result;
      this.isDone = Boolean.TRUE;
      lock.notifyAll();
    }
  }

  @Override
  public boolean finish() {
    return isDone;
  }
}
